﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.User;
using B.S.BasicData.Api.Read.DTOS;
using B.S.BasicData.Domain.Entity;
using B.S.BasicData.Domian.Entitys;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.Handler.User
{
    public class GetUserRoleHandler : IRequestHandler<GetUserRoleCommand, ApiResult<List<UserRoleDto>>>
    {
        private readonly IBaseRepository<UserRoleModel> _userroleRepository;
        private readonly IBaseRepository<UsersModel> _userRepository;
        private readonly IMapper _mapper;

        public GetUserRoleHandler(IBaseRepository<UserRoleModel> userroleRepository, IMapper mapper, IBaseRepository<UsersModel> userRepository)
        {
            _userroleRepository = userroleRepository;
            _mapper = mapper;
            _userRepository = userRepository;
        }
        /// <summary>
        ///获取用户角色
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<List<UserRoleDto>>> Handle(GetUserRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<UserRoleDto>> result = new ApiResult<List<UserRoleDto>>();

            //根据角色获取用户id集合
            var userIds = _userroleRepository.GetAll().Where(p => p.RoleId == request.RoleId).Select(p => p.UserId).ToList();
            //再根据用户id集合查出包含的用户信息
            var users = _userRepository.GetAll().Where(p => userIds.Contains(p.Id)).ToList();

            result.Code = StatusEnum.OK;
            result.Data = _mapper.Map<List<UserRoleDto>>(users);
            result.Message = "获取成功";
            return Task.FromResult(result);
        }
    }
}
